package com.pirestupppai.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blog.www.guideview.Component;
import com.blog.www.guideview.Guide;
import com.blog.www.guideview.GuideBuilder;
import com.pirestupppai.R;
import com.pirestupppai.adapter.ImageEditAdapter;
import com.pirestupppai.adapter.PsListAdapter;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.base.BaseApplication;
import com.pirestupppai.common.Constant;
import com.pirestupppai.imagetool.CustomStickerModel;
import com.pirestupppai.imagetool.CustomTextModel;
import com.pirestupppai.imagetool.DragView;
import com.pirestupppai.rxbus.RxBus;
import com.pirestupppai.utils.GuideComponent;
import com.pirestupppai.utils.SharedPreferenceUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.utils.WeakReferenceHandler;
import com.pirestupppai.widgets.dialog.ImageEditAddDialog;
import com.pirestupppai.widgets.dialog.ProgressingDialog;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.callback.BitmapLoadCallback;
import com.yalantis.ucrop.model.ExifInfo;
import com.yalantis.ucrop.util.BitmapLoadUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.pirestupppai.rxbus.RxBus.RXBUS_FINISH_ACTIVITY;

/**
 * 图片处理Activity
 */

public class ImageEditActivity extends BaseActivity {

    private final int RESULT_LOAD_IMAGE = 0x112;
    private final int RESULT_MATTING = 0x113;   // 抠图
    private final int RESULT_VIRTUAL = 0x123;   // 虚化
    private final int RESULT_PAINT = 0x133;     // 画笔
    private final int RESULT_COPY = 0x134;      // 仿制
    private final int RESULT_FILTER = 0x223;    // 滤镜

    private final int SELECT_LAYER = 0;          // 选中图层
    private final int DELETE_LAYER = 1;          // 删除图层

    private final int SELECT_TEXT = 0x12;        // 选择文字
    private final int SELECT_STICKER = 0x13;     // 选择贴纸

    private final int EDIT_ADD_IMAGE = 0x23;     // 添加贴纸
    private final int EDIT_ADD_TEXT = 0x24;      // 添加文字

    @BindView(R.id.back_btn)
    ImageView mBackBtn;
    @BindView(R.id.complete_btn)
    ImageView mCompleteBtn;
    @BindView(R.id.image_scroll_layout)
    RecyclerView mScrollImageLayout;
    @BindView(R.id.dragview)
    DragView mDragView;
    @BindView(R.id.drag_parent_layout)
    RelativeLayout mDragParentView;
    @BindView(R.id.image_crop_layout)
    RelativeLayout mImageCropLayout;
    @BindView(R.id.image_matting_layout)
    RelativeLayout mImageMattingLayout;
    @BindView(R.id.image_virtual_layout)
    RelativeLayout mImageVirtualLayout;
    @BindView(R.id.image_paint_layout)
    RelativeLayout mImagePaintLayout;
    @BindView(R.id.image_copy_layout)
    RelativeLayout mImageCopyLayout;
    @BindView(R.id.image_filter_layout)
    RelativeLayout mImageFilterLayout;
    @BindView(R.id.text_content_tv)
    TextView mTextContentTv;
    @BindView(R.id.text_style_tv)
    TextView mTextStyleTv;
    @BindView(R.id.text_size_tv)
    TextView mTextSizeTv;
    @BindView(R.id.text_color_tv)
    TextView mTextColorTv;
    @BindView(R.id.text_content_view)
    RelativeLayout mTextContentView;
    @BindView(R.id.text_style_view)
    RelativeLayout mTextStyleView;
    @BindView(R.id.text_size_view)
    RelativeLayout mTextSizeView;
    @BindView(R.id.text_color_view)
    RelativeLayout mTextColorView;
    @BindView(R.id.image_edit_type)
    LinearLayout mImageEditTypeLayout;
    @BindView(R.id.text_edit_type)
    RelativeLayout mTextEditTypeLayout;
    @BindView(R.id.text_content_et)
    EditText mTextContentEt;
    @BindView(R.id.first_text_style)
    TextView mFirstStyleTv;
    @BindView(R.id.second_text_style)
    TextView mSecondStyleTv;
    @BindView(R.id.third_text_style)
    TextView mThirdStyleTv;
    @BindView(R.id.text_size_seekbar)
    SeekBar mChangeTextSizeSeekbar;
    @BindView(R.id.red_layout)
    RelativeLayout mRedLayout;
    @BindView(R.id.green_layout)
    RelativeLayout mGreenLayout;
    @BindView(R.id.yellow_layout)
    RelativeLayout mYellowLayout;
    @BindView(R.id.black_layout)
    RelativeLayout mBlackLayout;
    @BindView(R.id.edit_bottom_view)
    RelativeLayout mBottomEditLayout;

    private int mAskId;            // 原图的id
    private int mCurrentLayerId = 0;                       // 当前选中的图层,如果为0，表示底图
    private ImageView mAddLayerBtn;     // 添加图层
    private int mAddImageSize = 400;                  // 从相册添加贴纸，压缩的宽度
    private RecyclerView.LayoutParams layoutParams;
    private LinearLayoutManager mLinearLayoutManager;
    private ImageEditAdapter mImageEditAdapter;
    public static List<CustomStickerModel> mImageList = new ArrayList<>();
    private ItemClickListener mItemClickListener;          // 顶部选择
    private LayerSelectListener layerSelectListener;       // 操作区域选择
    private String tempFilePath;                           // 图片裁剪时的，用于转换的文件路径
    private String tempFileName;
    private String tempDirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "tupai" + File.separator + "temp" + File.separator;
    private WeakReferenceHandler mHandler = new WeakReferenceHandler(this);
    private int selectTextTvIndex;    // 选择的文字操作类型
    private List<TextView> mTextSelectTvList = new ArrayList<>();
    private List<RelativeLayout> mTextSelectViewList = new ArrayList<>();
    private SelectTypeListener mSelectTypeListener;
    private String[] mFontStyleFileNames;
    private int selectTextStyleIndex;    // 选择的文字字体样式
    private List<TextView> mTextStyleList = new ArrayList<>();
    private List<RelativeLayout> mColorLayouts = new ArrayList<>();
    private int selectColorIndex;     // 选择的字体颜色
    private String[] paintColors = new String[]{"#FC0102", "#01CC33", "#FFFC33", "#000000"};

    private Typeface mSecondTypeface;
    private Typeface mThirdTypeface;

    /**
     * 由于较大的Bitmap不能通过Intent在Activity之间传递，所以设置此mDeliverBitmap
     * 图片处理页只是传递Bitmap，其他页面通过ImageEditActivity.mDeliverBitmap访问需要处理的Bitmap
     * 其他页面处理完毕后，返回之前需要设置mDeliverBitmap为处理后的Bitmap
     */
    public static Bitmap mDeliverBitmap;          // 其他页面图片处理时，传递Bitmap

    private Subscription mSubscription;
    private int mPsType;

    private Guide mGuideOperation;
    private ProgressingDialog mDialog;

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected void initListeners() {
        layerSelectListener = new LayerSelectListener();
        mDragView.setLayerListener(layerSelectListener);
        mSelectTypeListener = new SelectTypeListener();
        mDragView.setSelectTypeListener(mSelectTypeListener);
        mImageCropLayout.setOnClickListener(this);
        mImageMattingLayout.setOnClickListener(this);
        mImageVirtualLayout.setOnClickListener(this);
        mImagePaintLayout.setOnClickListener(this);
        mImageCopyLayout.setOnClickListener(this);
        mImageFilterLayout.setOnClickListener(this);
        mBackBtn.setOnClickListener(this);
        mCompleteBtn.setOnClickListener(this);

        mAddLayerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageEditAddDialog addDialog = new ImageEditAddDialog(mContext, mHandler);
                addDialog.show();
            }
        });

        mTextContentEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mDragView.ChangeText(mTextContentEt.getText().toString());
            }
        });

        mChangeTextSizeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                float textSize = Utils.dpToPx(mContext, ((float) progress / 50f) * 20f);
                mDragView.ChangeTextSize(textSize);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        for (selectColorIndex = 0; selectColorIndex < mColorLayouts.size(); selectColorIndex++) {
            mColorLayouts.get(selectColorIndex).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View currentLayout) {
                    int index;
                    for (index = 0; index < mColorLayouts.size(); index++) {
                        if (currentLayout == mColorLayouts.get(index)) {
                            break;
                        }
                    }
                    for (int i = 0; i < mColorLayouts.size(); i++) {
                        mColorLayouts.get(i).setBackground(null);
                    }
                    currentLayout.setBackgroundResource(R.drawable.shape_select_color_background);
                    mDragView.ChangeTextColor(Color.parseColor(paintColors[index]));
                }
            });
        }

        for (selectTextTvIndex = 0; selectTextTvIndex < mTextSelectTvList.size(); selectTextTvIndex++) {
            mTextSelectTvList.get(selectTextTvIndex).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View tv) {
                    int index;
                    for (index = 0; index < mTextSelectTvList.size(); index++) {
                        if (tv == mTextSelectTvList.get(index)) {
                            break;
                        }
                    }

                    for (int j = 0; j < mTextSelectTvList.size(); j++) {
                        mTextSelectTvList.get(j).setTextColor(Color.parseColor("#4A4A4A"));
                        mTextSelectViewList.get(j).setVisibility(View.GONE);
                    }
                    mTextSelectTvList.get(index).setTextColor(Color.parseColor("#FFDA00"));
                    mTextSelectViewList.get(index).setVisibility(View.VISIBLE);
                }
            });
        }

        for (selectTextStyleIndex = 0; selectTextStyleIndex < mTextStyleList.size(); selectTextStyleIndex++) {
            mTextStyleList.get(selectTextStyleIndex).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View styleTv) {
                    int index;
                    for (index = 0; index < mTextStyleList.size(); index++) {
                        if (styleTv == mTextStyleList.get(index)) {
                            break;
                        }
                    }

                    for (int j = 0; j < mTextStyleList.size(); j++) {
                        mTextStyleList.get(j).setTextColor(Color.parseColor("#000000"));
                        mTextStyleList.get(j).setBackgroundResource(R.drawable.shape_text_style_unselect);
                    }
                    mTextStyleList.get(index).setTextColor(Color.parseColor("#FFFFFF"));
                    mTextStyleList.get(index).setBackgroundResource(R.drawable.shape_text_style_select);
                    mDragView.ChangeTextStyle(index);
                }
            });
        }
    }

    @Override
    protected void initViews() {
        mItemClickListener = new ItemClickListener();

        mDialog = new ProgressingDialog(mContext);
        mAddLayerBtn = new ImageView(mContext);
        mAddLayerBtn.setImageResource(R.drawable.add_layer_btn);
        layoutParams = new RecyclerView.LayoutParams(Utils.dpToPx(mContext, 36), Utils.dpToPx(mContext, 36));
        layoutParams.setMargins(0, Utils.dpToPx(mContext, 2), 0, 0);
        mAddLayerBtn.setLayoutParams(layoutParams);

        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mImageEditAdapter = new ImageEditAdapter(mContext, mImageList);
        mImageEditAdapter.setLastView(mAddLayerBtn);
        mImageEditAdapter.setOnItemClickListener(mItemClickListener);

        mScrollImageLayout.setLayoutManager(mLinearLayoutManager);
        mScrollImageLayout.setAdapter(mImageEditAdapter);
        mScrollImageLayout.setHasFixedSize(true);

        mTextSelectTvList.add(mTextContentTv);
        mTextSelectTvList.add(mTextStyleTv);
        mTextSelectTvList.add(mTextSizeTv);
        mTextSelectTvList.add(mTextColorTv);

        mTextSelectViewList.add(mTextContentView);
        mTextSelectViewList.add(mTextStyleView);
        mTextSelectViewList.add(mTextSizeView);
        mTextSelectViewList.add(mTextColorView);

        mFontStyleFileNames = getAssetsFileName("fonts");
        mSecondTypeface = Typeface.createFromAsset(mContext.getAssets(), mFontStyleFileNames[0]);
        mThirdTypeface = Typeface.createFromAsset(mContext.getAssets(), mFontStyleFileNames[1]);
        mSecondStyleTv.setTypeface(mSecondTypeface);
        mThirdStyleTv.setTypeface(mThirdTypeface);

        mTextStyleList.add(mFirstStyleTv);
        mTextStyleList.add(mSecondStyleTv);
        mTextStyleList.add(mThirdStyleTv);

        mColorLayouts.add(mRedLayout);
        mColorLayouts.add(mGreenLayout);
        mColorLayouts.add(mYellowLayout);
        mColorLayouts.add(mBlackLayout);
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_image_edit;
    }

    @Override
    protected void initLogic() {
        //注册观察者
        mSubscription = RxBus.getInstance()
                .toObservable(RXBUS_FINISH_ACTIVITY, String.class)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        finish();
                    }
                });

        mAskId = getIntent().getIntExtra(Constant.IntentKey.PARENT_ID, 0);
        mPsType = getIntent().getIntExtra(Constant.IntentKey.PS_TYPE, PsListAdapter.PS_TYPE_REPLY_NOW);
        String path = getIntent().getStringExtra(Constant.IntentKey.SELECT_LIST);

        // 当前屏幕剩余高度
        int surplusHeight = Constant.HEIGHT_OF_SCREEN - Constant.HEIGHT_OF_STATUSBAR
                - Utils.dpToPx(mContext, 64) - Utils.dpToPx(mContext, 85);

        // 底图
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth() * surplusHeight / bitmap.getHeight(), surplusHeight, true);  // 图片压缩

        CustomStickerModel backgroundStickerModel = new CustomStickerModel(bitmap);
        mDragView.addBackgroundBitmap(backgroundStickerModel);
        mImageList.add(backgroundStickerModel);
        mImageEditAdapter.notifyDataSetChanged();

        mDragView.setLayerId(mCurrentLayerId);   // 设置底图为当前图层

        File file = new File(tempDirPath);
        if (!file.exists()) {
            file.mkdirs();
        }

        SharedPreferences sp = SharedPreferenceUtil.getSp();
        SharedPreferences.Editor editor = SharedPreferenceUtil.getEditor();
        boolean isFirstRun = sp.getBoolean(Constant.SPKey.FIRSTIMAGEEDITACTIVITY, true);
        if (isFirstRun) {
            editor.putBoolean(Constant.SPKey.FIRSTIMAGEEDITACTIVITY, false);
            editor.apply();
            // 引导层
            mAddLayerBtn.post(new Runnable() {
                @Override
                public void run() {
                    ShowAddGuideView();
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.image_crop_layout:
                mDialog.show();
                Observable.create(new Observable.OnSubscribe<Bitmap>() {
                    @Override
                    public void call(Subscriber<? super Bitmap> subscriber) {
                        Bitmap saveBitmap;
                        if (mCurrentLayerId == 0) {
                            saveBitmap = getBackgroundBitmap();
                        } else {
                            saveBitmap = mDragView.getAllLayer().get(mCurrentLayerId).bitmap;
                        }
                        subscriber.onNext(saveBitmap);
                        subscriber.onCompleted();
                    }
                }).flatMap(new Func1<Bitmap, Observable<String>>() {
                    @Override
                    public Observable<String> call(final Bitmap bitmap) {

                        long currentTime = System.currentTimeMillis();
                        tempFileName = "crop" + currentTime + ".jpg";
                        try {
                            tempFilePath = SaveBitmap(bitmap, tempDirPath, tempFileName);
                        } catch (IOException e) {
                            Utils.showToast(e.toString());
                        }
                        return Observable.just(tempFilePath);
                    }
                }).subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<String>() {
                            @Override
                            public void call(String filePath) {
                                mDialog.dismiss();
                                if (!filePath.equals("")) {
                                    final Uri uri = Uri.fromFile(new File(filePath));
                                    startCropActivity(uri);
                                } else {
                                    Utils.showToast("保存图片出错");
                                }
                            }
                        });
                break;
            case R.id.image_matting_layout:
                Intent mattingIntent = new Intent(ImageEditActivity.this, ImageMattingActivity.class);
                if (mCurrentLayerId == 0) {
                    mDeliverBitmap = getBackgroundBitmap();
                } else {
                    mDeliverBitmap = mDragView.getAllLayer().get(mCurrentLayerId).bitmap;
                }
                startActivityForResult(mattingIntent, RESULT_MATTING);
                break;
            case R.id.image_filter_layout:
                Intent filterIntent = new Intent(ImageEditActivity.this, ImageFilterActivity.class);
                mDeliverBitmap = mDragView.getAllLayer().get(mCurrentLayerId).bitmap;
                startActivityForResult(filterIntent, RESULT_FILTER);
                break;
            case R.id.image_virtual_layout:
                Intent virtualIntent = new Intent(ImageEditActivity.this, ImageVirtualActivity.class);
                mDeliverBitmap = mDragView.getAllLayer().get(mCurrentLayerId).bitmap;
                startActivityForResult(virtualIntent, RESULT_VIRTUAL);
                break;
            case R.id.image_paint_layout:
                Intent paintIntent = new Intent(ImageEditActivity.this, ImagePaintActivity.class);
                mDeliverBitmap = mDragView.getAllLayer().get(mCurrentLayerId).bitmap;
                startActivityForResult(paintIntent, RESULT_PAINT);
                break;
            case R.id.image_copy_layout:
                Intent copyIntent = new Intent(ImageEditActivity.this, ImageCopyActivity.class);
                mDeliverBitmap = mDragView.getAllLayer().get(mCurrentLayerId).bitmap;
                startActivityForResult(copyIntent, RESULT_COPY);
                break;
            case R.id.complete_btn:
                mDialog.show();
                Observable.create(new Observable.OnSubscribe<Bitmap>() {
                    @Override
                    public void call(Subscriber<? super Bitmap> subscriber) {
                        Bitmap saveBitmap = getBackgroundBitmap();
                        subscriber.onNext(saveBitmap);
                        subscriber.onCompleted();
                    }
                }).flatMap(new Func1<Bitmap, Observable<String>>() {
                    @Override
                    public Observable<String> call(final Bitmap bitmap) {

                        long currentTime = System.currentTimeMillis();
                        tempFileName = "crop" + currentTime + ".jpg";
                        try {
                            tempFilePath = SaveBitmap(bitmap, tempDirPath, tempFileName);
                        } catch (IOException e) {
                            Utils.showToast(e.toString());
                        }
                        return Observable.just(tempFilePath);
                    }
                }).subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<String>() {
                            @Override
                            public void call(String filePath) {
                                mDialog.dismiss();
                                if (!filePath.equals("")) {
                                    ArrayList<String> resultList = new ArrayList<>();
                                    resultList.add(filePath);

                                    Intent intent = new Intent();
                                    Bundle bundle = new Bundle();
                                    bundle.putStringArrayList(Constant.IntentKey.SELECT_LIST, resultList);
                                    bundle.putInt(Constant.IntentKey.RELEASE_TYPE, Constant.SELECT_TYPE_WORK);
                                    bundle.putInt(Constant.IntentKey.PARENT_ID, mAskId);
                                    bundle.putBoolean(Constant.IntentKey.IS_REPLY_NOW, true);
                                    intent.putExtras(bundle);
                                    intent.setClass(mContext, ReleaseActivity.class);
                                    startActivity(intent);
                                } else {
                                    Utils.showToast("保存文件出错");
                                }
                            }
                        });
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case EDIT_ADD_IMAGE:
                // 添加贴纸
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, RESULT_LOAD_IMAGE);
                break;
            case EDIT_ADD_TEXT:
                // 添加文字
                mDragView.addText();
                mImageEditTypeLayout.setVisibility(View.GONE);
                mTextEditTypeLayout.setVisibility(View.VISIBLE);
                break;
        }
        return true;
    }

    /**
     * 获取背景bitmap，考虑当前显示时的缩放
     */
    private Bitmap getBackgroundBitmap() {
        CustomStickerModel backgroundImage = mDragView.getLayer(0);
        Matrix matrix = backgroundImage.matrix;
        float[] values = new float[10];
        matrix.getValues(values);
        float scaleX = values[0];    // 宽度缩放比例
        float scaleY = values[4];    // 高度缩放比例
        Bitmap mBackgroundTransBitmp = Bitmap.createBitmap((int) (backgroundImage.bitmap.getWidth() * scaleX),
                (int) (backgroundImage.bitmap.getHeight() * scaleY), Bitmap.Config.ARGB_8888);
        Canvas mBackgroundCanvas = new Canvas(mBackgroundTransBitmp);
        for (int i = 0; i < mDragView.getAllLayer().size(); i++) {
            CustomStickerModel customStickerModel = mDragView.getLayer(i);
            mBackgroundCanvas.drawBitmap(customStickerModel.bitmap, customStickerModel.matrix, null);
        }
        List<CustomTextModel> customTexts = mDragView.getAllText();

        // 画Text
        for (int i = 0; i < customTexts.size(); i++) {
            CustomTextModel customTextModel = customTexts.get(i);
            if (customTextModel.textStyle == 0) {
                customTextModel.textPaint.setTypeface(Typeface.DEFAULT);
            } else if (customTextModel.textStyle == 1) {
                customTextModel.textPaint.setTypeface(mSecondTypeface);
            } else if (customTextModel.textStyle == 2) {
                customTextModel.textPaint.setTypeface(mThirdTypeface);
            }
            mBackgroundCanvas.drawText(customTextModel.textString, customTextModel.textMarginLeft, customTextModel.textMarginTop, customTextModel.textPaint);
        }
        return mBackgroundTransBitmp;
    }

    /**
     * 顶部Adapter中选中图层
     */
    class ItemClickListener implements ImageEditAdapter.OnItemClickListener {
        public void onItemClick(int position) {
            mCurrentLayerId = position;
            mImageEditAdapter.notifyDataSetChanged();
            mDragView.setLayerId(mCurrentLayerId);
        }
    }

    /**
     * 图层操作区域选中图层
     */
    class LayerSelectListener implements DragView.LayerSelectListener {
        public void OnLayerSelect(int layerId, int type) {
            if (type == SELECT_LAYER) {
                mCurrentLayerId = layerId;
                mImageEditAdapter.setLayerId(mCurrentLayerId);
                mImageEditAdapter.notifyDataSetChanged();
            } else if (type == DELETE_LAYER) {
                mCurrentLayerId = 0;
                mImageList.remove(layerId);
                mImageEditAdapter.setLayerId(mCurrentLayerId);
                mImageEditAdapter.notifyDataSetChanged();
            }

        }
    }

    /**
     * 图层选择类型
     */
    class SelectTypeListener implements DragView.SelectTypeListener {
        public void OnSelectType(int selectType, String textStr, int textStyle, float textSize, int textColor) {
            if (selectType == SELECT_TEXT) {
                mImageEditTypeLayout.setVisibility(View.GONE);
                mTextEditTypeLayout.setVisibility(View.VISIBLE);
                mTextContentEt.setText(textStr);

                for (int j = 0; j < mTextStyleList.size(); j++) {
                    mTextStyleList.get(j).setTextColor(Color.parseColor("#000000"));
                    mTextStyleList.get(j).setBackgroundResource(R.drawable.shape_text_style_unselect);
                    mColorLayouts.get(j).setBackground(null);
                }
                int colorIndex = 0;
                for (; colorIndex < paintColors.length; colorIndex++) {
                    if (textColor == Color.parseColor(paintColors[colorIndex])) {
                        break;
                    }
                }
                mColorLayouts.get(colorIndex).setBackgroundResource(R.drawable.shape_select_color_background);
                mTextStyleList.get(textStyle).setTextColor(Color.parseColor("#FFFFFF"));
                mTextStyleList.get(textStyle).setBackgroundResource(R.drawable.shape_text_style_select);

                int progress = (int) (Utils.pxToDp(mContext, textSize) / 20f * 50f);
                mChangeTextSizeSeekbar.setProgress(progress);

            } else if (selectType == SELECT_STICKER) {
                mTextEditTypeLayout.setVisibility(View.GONE);
                mImageEditTypeLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RESULT_LOAD_IMAGE:
                    // 选择添加贴纸
                    if (null != data) {
                        Uri selectedImage = data.getData();
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};

                        Cursor cursor = getContentResolver().query(selectedImage,
                                filePathColumn, null, null, null);
                        cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String picturePath = cursor.getString(columnIndex);
                        cursor.close();

                        Log.d("", "select_image" + picturePath);

                        Bitmap imageBitmap = BitmapFactory.decodeFile(picturePath);
                        // 比例压缩
                        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, mAddImageSize,
                                (int) (mAddImageSize * (float) imageBitmap.getHeight() / (float) imageBitmap.getWidth()), true);

                        CustomStickerModel customStickerModel = new CustomStickerModel(imageBitmap);
                        mDragView.addBitmap(customStickerModel);

                        mImageList.add(customStickerModel);
                        mCurrentLayerId = mImageList.size() - 1;
                        mImageEditAdapter.setLayerId(mCurrentLayerId);
                        mImageEditAdapter.notifyDataSetChanged();

                        mDragView.setLayerId(mCurrentLayerId);   // 设置当前的图层为底图
                    }
                    break;
                case UCrop.REQUEST_CROP:
                    // 裁剪
                    handleCropResult(data);
                    final Uri resultUri = UCrop.getOutput(data);

                    int maxBitmapSize = BitmapLoadUtils.calculateMaxBitmapSize(ImageEditActivity.this);

                    BitmapLoadUtils.decodeBitmapInBackground(ImageEditActivity.this, resultUri, null, maxBitmapSize, maxBitmapSize,
                            new BitmapLoadCallback() {

                                @Override
                                public void onBitmapLoaded(@NonNull Bitmap bitmap, @NonNull ExifInfo exifInfo, @NonNull String imageInputPath, @Nullable String imageOutputPath) {
                                    if (mCurrentLayerId == 0) {
                                        mImageList.clear();
                                        CustomStickerModel customStickerModel = new CustomStickerModel(bitmap);
                                        mImageList.add(customStickerModel);
                                        mImageEditAdapter.notifyDataSetChanged();
                                        mDragView.removeAllLayer();
                                        mDragView.addBackgroundBitmap(customStickerModel);
                                        // 移除所有的文字
                                        mDragView.removeAllText();
                                        // view的宽高发生变化，需要重新布局
                                        mDragView.requestLayout();
                                        mDragView.invalidate();
                                    } else {
                                        mImageList.get(mCurrentLayerId).bitmap = bitmap;
                                        mImageEditAdapter.notifyDataSetChanged();
                                        CustomStickerModel customBitmap = new CustomStickerModel(bitmap);
                                        mDragView.repleaceLayer(mCurrentLayerId, customBitmap);
                                        mDragView.setLayerId(mCurrentLayerId);
                                        mDragView.requestLayout();
                                        mDragView.invalidate();
                                    }
                                }

                                @Override
                                public void onFailure(@NonNull Exception bitmapWorkerException) {
                                }
                            });
                    // 删除缓存文件
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            RecursionDeleteFile(new File(tempDirPath));
                        }
                    }, 3000);
                    break;
                case RESULT_MATTING:
                    // 抠图
                    mImageList.get(mCurrentLayerId).bitmap = mDeliverBitmap;
                    if (mCurrentLayerId == 0) {
                        if (mImageList.size() > 1) {
                            int length = mImageList.size();
                            for (int i = 1; i < length; i++) {
                                mImageList.remove(1);
                            }
                        }
                        CustomStickerModel customStickerModel = new CustomStickerModel(mDeliverBitmap);
                        mDragView.removeAllLayer();
                        mDragView.addBackgroundBitmap(customStickerModel);
                        // 移除所有的文字
                        mDragView.removeAllText();
                        mDragView.requestLayout();
                        mDragView.invalidate();
                    } else {
                        CustomStickerModel customBitmap = new CustomStickerModel(mDeliverBitmap);
                        mDragView.repleaceLayer(mCurrentLayerId, customBitmap);
                        mDragView.setLayerId(mCurrentLayerId);
                        mDragView.requestLayout();
                        mDragView.invalidate();
                    }
                    mImageEditAdapter.notifyDataSetChanged();
                    break;
                case RESULT_FILTER:
                    // 滤镜
                    mImageList.get(mCurrentLayerId).bitmap = mDeliverBitmap;
                    mDragView.getLayer(mCurrentLayerId).bitmap = mDeliverBitmap;
                    mImageEditAdapter.notifyDataSetChanged();
                    mDragView.invalidate();
                    break;
                case RESULT_VIRTUAL:
                    // 虚化
                    mImageList.get(mCurrentLayerId).bitmap = mDeliverBitmap;
                    mDragView.getLayer(mCurrentLayerId).bitmap = mDeliverBitmap;
                    mImageEditAdapter.notifyDataSetChanged();
                    mDragView.invalidate();
                    break;
                case RESULT_PAINT:
                    // 画笔
                    mImageList.get(mCurrentLayerId).bitmap = mDeliverBitmap;
                    mDragView.getLayer(mCurrentLayerId).bitmap = mDeliverBitmap;
                    mImageEditAdapter.notifyDataSetChanged();
                    mDragView.invalidate();
                    break;
                case RESULT_COPY:
                    // 仿制
                    mImageList.get(mCurrentLayerId).bitmap = mDeliverBitmap;
                    mDragView.getLayer(mCurrentLayerId).bitmap = mDeliverBitmap;
                    mImageEditAdapter.notifyDataSetChanged();
                    mDragView.invalidate();
                    break;
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            handleCropError(data);
        }
    }

    private void startCropActivity(@NonNull Uri uri) {
        Toast.makeText(mContext, "开始裁剪", Toast.LENGTH_SHORT).show();

        UCrop uCrop = UCrop.of(uri, Uri.fromFile(new File(tempDirPath, tempFileName)));

        uCrop.useSourceImageAspectRatio();
        UCrop.Options options = new UCrop.Options();
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        options.setCompressionQuality(90);

        options.setHideBottomControls(false);
        options.setFreeStyleCropEnabled(false);
        uCrop.withOptions(options);

        uCrop.start(ImageEditActivity.this);
    }

    /**
     * 保存bitmap到本地
     */
    private String SaveBitmap(Bitmap bitmap, String filePath, String fileName) throws IOException {
        File file = new File(filePath, fileName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
            return "";
        } catch (IOException e) {
            Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
            return "";
        }
        return filePath + fileName;
    }

    private void handleCropResult(@NonNull Intent result) {
        final Uri resultUri = UCrop.getOutput(result);
        if (resultUri != null) {
//            ResultActivity.startWithUri(SampleActivity.this, resultUri);
//            Toast.makeText(SampleActivity.this, "拿到数据", Toast.LENGTH_SHORT).show();

        } else {
            Toast.makeText(ImageEditActivity.this, "Cannot retrieve cropped image", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    private void handleCropError(@NonNull Intent result) {
        final Throwable cropError = UCrop.getError(result);
        if (cropError != null) {
            Toast.makeText(ImageEditActivity.this, cropError.getMessage(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(ImageEditActivity.this, "Unexpected error", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 递归删除文件夹下的所有文件
     */
    public void RecursionDeleteFile(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                file.delete();
                return;
            }
            for (File f : childFile) {
                RecursionDeleteFile(f);
            }
            // 不删除文件夹
//            file.delete();
        }
    }

    /**
     * 读取Assets一个文件夹下的所有文件名
     */
    public static String[] getAssetsFileName(String dirName) {
        AssetManager assets = null;
        String[] fileNames = null;
        try {
            assets = BaseApplication.getAppContext().getAssets();
            //获取/assets/目录下所有文件
            fileNames = assets.list(dirName);

            for (int i = 0; i < fileNames.length; i++) {
                fileNames[i] = dirName + "/" + fileNames[i];
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileNames;
    }

    public void ShowAddGuideView() {
        GuideBuilder builder = new GuideBuilder();
        builder.setTargetView(mAddLayerBtn)
                .setAlpha(150)
                .setHighTargetCorner(20)
                .setHighTargetPadding(8)
                .setOverlayTarget(false)
                .setOutsideTouchable(false);
        builder.setOnVisibilityChangedListener(new GuideBuilder.OnVisibilityChangedListener() {
            @Override
            public void onShown() {
            }

            @Override
            public void onDismiss() {
                ShowBottomView();
            }
        });
        builder.addComponent(new GuideComponent(mContext, "点击添加新图层", Component.ANCHOR_BOTTOM, Component.FIT_START, -40, 40));
        mGuideOperation = builder.createGuide();
        mGuideOperation.setShouldCheckLocInWindow(false);
        mGuideOperation.show(ImageEditActivity.this);
    }

    public void ShowBottomView() {
        GuideBuilder builder = new GuideBuilder();
        builder.setTargetView(mBottomEditLayout)
                .setAlpha(150)
                .setHighTargetCorner(20)
                .setHighTargetPaddingLeft(20)
                .setHighTargetPaddingRight(20)
                .setHighTargetPaddingBottom(25)
                .setOverlayTarget(false)
                .setOutsideTouchable(false);
        builder.addComponent(new GuideComponent(mContext, "利用下面的工具编辑你选中的图层", Component.ANCHOR_TOP, Component.FIT_START, 50, -40));
        mGuideOperation = builder.createGuide();
        mGuideOperation.setShouldCheckLocInWindow(false);
        mGuideOperation.show(ImageEditActivity.this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mImageList.clear();
        if (!mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
        }
    }
}
